package com.ruoyi.project.system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.TreeSelect;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.mapper.SysOrganizeMapper;
import com.ruoyi.project.system.domain.SysOrganize;
import com.ruoyi.project.system.service.ISysOrganizeService;

/**
 * 组织结构Service业务层处理
 * 
 * @author frank
 * @date 2024-08-26
 */
@Service
public class SysOrganizeServiceImpl implements ISysOrganizeService 
{
    @Autowired
    private SysOrganizeMapper sysOrganizeMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * 查询组织结构
     * 
     * @param organizeId 组织结构主键
     * @return 组织结构
     */
    @Override
    public SysOrganize selectSysOrganizeByOrganizeId(String organizeId)
    {
        return sysOrganizeMapper.selectSysOrganizeByOrganizeId(organizeId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param organize 部门信息
     * @return 结果
     */
    @Override
    public boolean checkOrganizeNameUnique(SysOrganize organize)
    {
//        String organizeId = StringUtils.isNull(organize.getOrganizeId()) ? "" : organize.getOrganizeId();
        SysOrganize info = sysOrganizeMapper.checkOrganizeNameUnique(organize.getOrgno(), organize.getOrgname());
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 是否存在子节点
     *
     * @param organizeId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByOrganizeId(String organizeId)
    {
        int result = sysOrganizeMapper.hasChildByOrganizeId(organizeId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param organizeId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkOrganizeExistUser(String organizeId)
    {
        int result = sysOrganizeMapper.checkOrganizeExistUser(organizeId);
        return result > 0;
    }

    /**
     * 校验组织是否有数据权限
     *
     * @param organizeId 组织id
     */
    @Override
    public void checkOrganizeDataScope(String organizeId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(organizeId))
        {
            SysOrganize organize = new SysOrganize();
            organize.setOrganizeId(organizeId);
            List<SysOrganize> organizes = selectSysOrganizeList(organize);
            if (StringUtils.isEmpty(organizes))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }
    /**
     * 查询组织结构列表
     * 
     * @param sysOrganize 组织结构
     * @return 组织结构
     */
    @Override
    @DataScope(organizeAlias = "s")
    public List<SysOrganize> selectSysOrganizeList(SysOrganize sysOrganize)
    {
        List<SysOrganize> sysOrganizeList = sysOrganizeMapper.selectSysOrganizeList(sysOrganize);
        List<SysOrganize> other = new ArrayList<>(sysOrganizeList.size());
        other.addAll(sysOrganizeList);
        sysOrganizeList.forEach(x->{
            if(x.getJsdwId() != null && x.getJsdwId().length() > 0){
                x.setJsdwName(other.stream().filter(t->t.getOrganizeId().equals(x.getJsdwId())).findFirst().get().getOrgname());
            }
            if(x.getFhdwId() != null && x.getFhdwId().length() > 0){
                x.setFhdwName(other.stream().filter(t->t.getOrganizeId().equals(x.getFhdwId())).findFirst().get().getOrgname());
            }
        });
        return sysOrganizeList;
    }
    /**
     * 根据角色ID查询组织树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<String> selectOrganizeListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return sysOrganizeMapper.selectOrganizeListByRoleId(roleId, role.isDeptCheckStrictly());
    }
    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectOrganizeTreeList(SysOrganize dept)
    {
        List<SysOrganize> depts = SpringUtils.getAopProxy(this).selectSysOrganizeList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
//    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysOrganize> depts)
    {
        List<SysOrganize> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
//    @Override
    public List<SysOrganize> buildDeptTree(List<SysOrganize> depts)
    {
        List<SysOrganize> returnList = new ArrayList<SysOrganize>();
        List<String> tempList = depts.stream().map(SysOrganize::getOrganizeId).collect(Collectors.toList());
        for (SysOrganize dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<SysOrganize> list, SysOrganize t)
    {
        // 得到子节点列表
        List<SysOrganize> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysOrganize tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<SysOrganize> getChildList(List<SysOrganize> list, SysOrganize t)
    {
        List<SysOrganize> tlist = new ArrayList<SysOrganize>();
        Iterator<SysOrganize> it = list.iterator();
        while (it.hasNext())
        {
            SysOrganize n = (SysOrganize) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getOrganizeId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysOrganize> list, SysOrganize t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 新增组织结构
     * 
     * @param sysOrganize 组织结构
     * @return 结果
     */
    @Override
    public int insertSysOrganize(SysOrganize sysOrganize)
    {
        return sysOrganizeMapper.insertSysOrganize(sysOrganize);
    }

    /**
     * 修改组织结构
     * 
     * @param sysOrganize 组织结构
     * @return 结果
     */
    @Override
    public int updateSysOrganize(SysOrganize sysOrganize)
    {
        return sysOrganizeMapper.updateSysOrganize(sysOrganize);
    }

    /**
     * 批量删除组织结构
     * 
     * @param organizeIds 需要删除的组织结构主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizeByOrganizeIds(String[] organizeIds)
    {
        return sysOrganizeMapper.deleteSysOrganizeByOrganizeIds(organizeIds);
    }

    /**
     * 删除组织结构信息
     * 
     * @param organizeId 组织结构主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizeByOrganizeId(String organizeId)
    {
        return sysOrganizeMapper.deleteSysOrganizeByOrganizeId(organizeId);
    }
}
